package pres.wchen.oa.cor.shiro.web.wx;

import net.sf.json.JSONObject;
import org.jeewx.api.core.common.WxstoreUtils;
import org.jeewx.api.third.JwThirdAPI;
import org.jeewx.api.third.model.ApiAuthorizerToken;
import org.jeewx.api.third.model.ApiAuthorizerTokenRet;
import org.jeewx.api.third.model.ApiComponentToken;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * @作者： wchen
 * @描述：
 * @创建时间： 2018/1/29 14:09
 * @版本：Copyright 2018, Inc. All Rights Reserved.
 * @修改信息：
 */
public class WxUtil {
//    private static String appID = "wx096c93642d778d3f";
//    private static String appsecret = "58b16e642e5f753fb847889d9f3c2648";
//    public static String token = "6_rfpggSymrNDB8-oWEGb3gOJlsiMKS5lA_HmGNvvJT6TcD_kqXHt-YvK1YUBNwYQFQCj0UoKX5wfyRUPxwc0mq1T5yHoZbhDeKlTxRvMTSH2VoeUqravqeJYTR4N1lfI5XAXH_AwW9n4r5gAnIBDdAGAATV";

    private static String appID = "wxba102761606e7496";
    private static String appsecret = "37c9d3eefe04e5f8bc71d41178c09e40";
    public static String token = "6_5-Y8nVRNmcVbV-tLKIRVU1PXeco1GWt_GVlk5bKZNK3YKcq_p9hk9wRv1snkGULRwBFED5NbmdN5YB57GLYIz6I7C_3Qk433ZPR78HlH1uyiE3Z3p3I1dzfXtNQP5i2yvlGBfwO03yRd8b4kACTeADAGIZ";
    public static String CREATE_CARD_URL = "https://api.weixin.qq.com/card/create?access_token=ACCESS_TOKEN";
    public static String TICKET = "HoagFKDcsGMVCIY2vOjf9lHwfa1ia4Ez6RtWV_N3Ou1DK8Bv4wsMrkfe2bkeRFc4uk54oxNx2z7FSb9WpXob0w";
    /**
     *
     * @描述： 获取token
     * @名称： getAccessToken
     * @入参： []
     * @出参： void
     * @修改信息： 创建：wchen 2018/1/29
     */
    public static void getAccessToken(){

        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appID +"&secret=" + appsecret;
        JSONObject result = WxstoreUtils.httpRequest(url, "GET", null);
        System.out.println(result.toString());
    }

    /**
     *
     * @描述：  获取JsapiTicket
     * @名称： getJsapiTicket
     * @入参： []
     * @出参： java.lang.String
     * @修改信息： 创建：wchen 2018/1/29
     */
    public static String getJsapiTicket(){

        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
        String requestUrl = url.replace("ACCESS_TOKEN", WxUtil.token);
        JSONObject result = WxstoreUtils.httpRequest(requestUrl, "GET", null);
        System.out.println(result.toString());
        return result.get("ticket").toString();
    }

    /**
     *
     * @描述： 向微信发送接口请求  post
     * @名称： httpRequestWx
     * @入参： [url, authorizerAccessToken, paramObj]
     * @出参： net.sf.json.JSONObject
     * @修改信息： 创建：wchen 2018/1/29
     */
    public static JSONObject httpRequestWx(String url, String authorizerAccessToken, Object paramObj) {

        String requestUrl = url.replace("ACCESS_TOKEN", authorizerAccessToken);
        JSONObject param = JSONObject.fromObject(paramObj);
        JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", param.toString());
        return result;
    }


    /**
     *
     * @描述： 向微信发送接口请求 get
     * @名称： httpRequestWxGet
     * @入参： [url, authorizerAccessToken]
     * @出参： net.sf.json.JSONObject
     * @修改信息： 创建：wchen 2018/1/29
     */
    public static JSONObject httpRequestWxGet(String url, String authorizerAccessToken) {

        String requestUrl = url.replace("TOKEN", authorizerAccessToken);
        String paramStr = null;
        JSONObject result = WxstoreUtils.httpRequest(requestUrl, "GET", paramStr);
        return result;
    }



    /**
     *  @描述: 获取签名
     *  @参数： [skipUrl]
     *  @返回值： java.util.Map<java.lang.String,java.lang.Object>
     *  @创建人: wchen
     *  @创建时间: 2018/1/29
     *  @修改人和其它信息:
     */
    public static Map<String, Object> getSignature(String skipUrl){

        String nonceStr = "abcdefghijklmnobqrstuvwxyz";
        String jsApiTicket = TICKET;
        String timeStamp = Long.toString(System.currentTimeMillis()/1000);
//        String url = "http://mp.weixin.qq.com?params=value";
        StringBuffer sbf = new StringBuffer("jsapi_ticket=")
                .append(jsApiTicket)
                .append("&noncestr=")
                .append(nonceStr)
                .append("×tamp=")
                .append(timeStamp)
                .append("&url=")
                .append(skipUrl)
                ;
        String signature = "";
        try{
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(sbf.toString().getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        }catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println("***signature is " + signature);
        Map resultMap = new HashMap();
        resultMap.put("url", skipUrl);
        resultMap.put("jsapi_ticket", jsApiTicket);
        resultMap.put("nonceStr", nonceStr);
        resultMap.put("timestamp", timeStamp);
        resultMap.put("signature", signature);


        return resultMap;
    }


    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash){
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }



    public static void main(String[] args) {
//        getAccessToken();
//        getJsapiTicket();
//        System.out.println(getSignature("www.baidu.com").toString());
        createSign();
    }


    private static void createSign(){
        WxCardSign signer = new WxCardSign();
        signer.AddData("test1");
        signer.AddData(12312312);
        signer.AddData(55312312);
        signer.AddData("test");
        signer.AddData("test2");
        System.out.println(signer.GetSignature());
    }

}
